package com.token.sysflow.hander;
import com.alibaba.fastjson.JSONObject;
import com.token.base.Pl;
import com.token.sql.IntegrateSql;
import com.token.sql.PrepareSql;
import com.token.sysflow.bean.FSysSendMessage;
import com.token.sysflow.bean.FlowStepNotifySub;

import com.token.sysflow.service.JavaScriptUtil;
import lombok.Setter;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 
 */
public class Notify {
    private final FSysSendMessage sendMessage;
    private FlowStepNotifySub notifySub;
    @Setter
    private String actionUserId;
    @Setter
    private Step step;
    @Setter
    private String sendType;
    @Setter
    private String subject;
    @Setter
    private String message;
    @Setter
    private String org;

    @Setter
    private List<String> sendUsers;

    public Notify(IntegrateSql integrateSql) throws Exception{
        sendMessage = new FSysSendMessage(integrateSql);
        sendType = "sms";
        sendUsers = new ArrayList<>();
        sendMessage.setInsert();
    }

    /**
     *
     * @throws Exception
     */
    public void insertConfigNotify(ApproveProcess process, String[] approveUser, JSONObject fieldJson) throws Exception {
        this.sendType = step.getNotifyWay();
        notifySub = new FlowStepNotifySub(sendMessage.getIntegrateSql());
        PrepareSql pSql = new PrepareSql(sendMessage.getIntegrateSql());

        pSql.setPrepare(notifySub.selectCode().append(" where StepId=? "));
        pSql.setPstValue(1,step.getStepId());
        ResultSet rs = pSql.executeQuery();
        if(rs.next()){
            do{
                notifySub.initParamToRs(rs);
                this.subject = (String) JavaScriptUtil.execute(JavaScriptUtil.replaceStr(notifySub.getNotifySubject(),fieldJson));
                this.message = (String) JavaScriptUtil.execute(JavaScriptUtil.replaceStr(notifySub.getNotifyContext(),fieldJson));
                String t = notifySub.getNotifyObject();

                if(t.equals("0")){ //指定人
                    PrepareSql pSql1 = new PrepareSql(sendMessage.getIntegrateSql());
                    pSql1.setPrepare("SELECT Value FROM Flow_StepNotifyVth WHERE NotifyID=? AND FieldName='ApproverPeople'");
                    pSql1.setPstValue(1,notifySub.getKeyId());
                    ResultSet rs1 = pSql1.executeQuery();
                    while (rs1.next()){
                        sendUsers.add(rs1.getString("Value"));
                    }
                    rs1.close();
                    pSql1.close();
                }else if(t.equals("1")){//指定部门
                    //TODO 知会配置的指定部门未开发
                    //SELECT * FROM Flow_StepNotifyVth WHERE NotifyID=? AND FieldName='NotifyPosts'
                }else if(t.equals("2")){//起草人或申请人
                    String[] ss = notifySub.getCreOrApply().split(";");
                    if(ss.length == 2){
                        sendUsers.add(process.getCreater());
                        sendUsers.add(process.getApplyer());
                    }else if(ss.length == 1){
                        if(ss[0].equals("0")){
                            sendUsers.add(process.getCreater());
                        }else{
                            sendUsers.add(process.getApplyer());
                        }
                    }
                }else if(t.equals("3")){//过程办理人
//                    pSql1.setPrepare("SELECT Value FROM Flow_StepNotifyVth WHERE NotifyID=? AND FieldName='ApproverPeople'");
//                    pSql1.setPstValue(1,notifySub.getKeyId());
//                    ResultSet rs1 = pSql1.executeQuery();
//                    while (rs1.next()){
//                        sendUsers.add(rs1.getString("Value"));
//                    }
//                    rs1.close();
                    //TODO 知会配置的过程办理人未开发
                }else if(t.equals("4")){//待办人
                    sendUsers.addAll(Arrays.asList(approveUser));
                }else if(t.equals("5")){//指定人字段
                    //TODO 知会配置的指定人字段未开发
                }
                writeMessage();
            }while(rs.next());
        }

    }

    /**
     *
     * @throws Exception
     */
    public void insertSystemNotify()throws Exception {
        writeMessage();
    }


    /**
     *
     * @param sendUser
     */
    public void addSendUsers(String sendUser){
        sendUsers.add(sendUser);
    }

    /**
     *
     * @throws Exception
     */
    private void writeMessage()throws Exception{

        sendMessage.setSysId(Pl.getSysId());//租户ID
        sendMessage.setSysAddTime(Pl.getCurDataTime()); //创建时间
        sendMessage.setSysAddUser(actionUserId); //创建人
        sendMessage.setSysEditTime(Pl.getCurDataTime()); //修改时间
        sendMessage.setSysEditUser(actionUserId); //修改人
        sendMessage.setSubject(subject); //标题
        sendMessage.setMessage(message); //消息内容
        sendMessage.setSendType(sendType); //发送类型 sms,mail,weixin,phone
        sendMessage.setStatus(0); //状态(0未，1成功， 2失败)
        sendMessage.setOrg(org); //组织(公司、部门、岗位)
        sendMessage.setUserId(String.join(",", sendUsers)); //用户
        if(step != null) {
            sendMessage.setFlowId(step.getFlowId()); //流程Id
            sendMessage.setStepId(step.getStepId()); //环节Id
        }
        sendMessage.executeUpdate();
    }

    /**
     *
     */
    public void close(){
        try {
            sendMessage.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}